package com.jingzhe.core.utils;

import com.jingzhe.core.constant.ErrorCodeConstant;
import com.jingzhe.core.web.converter.Result;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据校验信息
 * @author wanghj
 *
 */
public class ErrorMsgUtil {
    private static Map<String, String> msgConverter(List<ObjectError> errors) {
        Map<String, String> errorMsgMap = new HashMap<String, String>();
        for(ObjectError error : errors){
            if (error instanceof FieldError) {
                errorMsgMap.put(((FieldError) error).getField(), error.getDefaultMessage());
            }          
        }
        return errorMsgMap;
    }

    public static <T> Result<T> invalidResult(BindingResult bindingResult) {
        Result<T> result = new Result<T>(null);
        result.setMsg("数据校验错误");
        result.setErrorCode(ErrorCodeConstant.VALIDATION_FAILED);
        result.setSuccess(false);
        result.setErrorMap(msgConverter(bindingResult.getAllErrors()));
        return result;
    }
}
